<?php

namespace app\notify\controller;

use app\common\Manage;
use app\notify\model\Customer;
use think\cache\driver\Redis;
use think\Controller;

/*
 * 云朵对接接口
 * */

class Cloud extends Controller
{


    private $customerList=array();
    private $token = "f9e9fc91ec782cb5ebdbb66262b409b1";
    public $file_val = array(
//        ["keys"=>'uniqueCustomerId', "value"=>"客户数据库ID", "encry"=>false],
        ["keys" => 'tmk_data', "value" => "是否为TMK数据", "encry" => false],
        ["keys" => 'fc_6287', "value" => "客户需求", "encry" => false],
        ["keys" => 'fc_6210', "value" => "学历", "encry" => false],
        ["keys" => 'fc_6007', "value" => "所在国家", "encry" => false],
        ["keys" => 'remarks', "value" => "备注信息", "encry" => false],
        ["keys" => 'fc_5541', "value" => "被其它机构联系", "encry" => false],
        ["keys" => 'chatUrl', "value" => "对话页链接", "encry" => false],
        ["keys" => 'totalCallSeconds', "value" => "总通话时长", "encry" => false],
        ["keys" => 'matchPattern', "value" => "匹配模式", "encry" => false],
        ["keys" => 'fc_4912', "value" => "手机号码2", "encry" => true],
        ["keys" => 'fc_4909', "value" => "退费金额", "encry" => false],
        ["keys" => 'fc_4893', "value" => "电话区号", "encry" => false],
        ["keys" => 'fc_4673', "value" => "成交金额", "encry" => false],
        ["keys" => 'fc_4655', "value" => "班级类型", "encry" => false],
        ["keys" => 'fc_4609', "value" => "是否接通", "encry" => false],
        ["keys" => 'fc_4525', "value" => "页面链接", "encry" => false],
        ["keys" => 'fc_4495', "value" => "推广版位", "encry" => false],
        ["keys" => 'phone', "value" => "联系电话", "encry" => true],
        ["keys" => 'workYears', "value" => "工作年限", "encry" => false],
        ["keys" => 'career', "value" => "职业", "encry" => false],
        ["keys" => 'graduateDate', "value" => "毕业日期", "encry" => false],
        ["keys" => 'majorCourse', "value" => "所学专业", "encry" => false],
        ["keys" => 'graduateSchool', "value" => "毕业院校", "encry" => false],
        ["keys" => 'degreeType', "value" => "学历类型", "encry" => false],
        ["keys" => 'birthdate', "value" => "出生日期", "encry" => false],
        ["keys" => 'nationality', "value" => "民族", "encry" => false],
        ["keys" => 'imSourceWay', "value" => "好友来源(IM)", "encry" => false],
        ["keys" => 'fc_4406', "value" => "邮寄资料", "encry" => false],
        ["keys" => 'fc_4405', "value" => "邮寄地址", "encry" => false],
        ["keys" => 'fc_4389', "value" => "客户等级", "encry" => false],
        ["keys" => 'spreadProvince', "value" => "线索省份", "encry" => false],
        ["keys" => 'spreadCity', "value" => "线索城市", "encry" => false],
        ["keys" => 'leads_type', "value" => "线索类型", "encry" => false],
        ["keys" => 'customerDealAmount', "value" => "成交总额", "encry" => false],
        ["keys" => 'customerLatestPayTime', "value" => "最近支付时间", "encry" => false],
        ["keys" => 'totalDealAmount', "value" => "已缴总额", "encry" => false],
        ["keys" => 'totalDebtAmount', "value" => "欠款总额", "encry" => false],
        ["keys" => 'totalDepositAmount', "value" => "定金总额", "encry" => false],
        ["keys" => 'fc_4303', "value" => "备注", "encry" => false],
        ["keys" => 'sourceUrl', "value" => "线索省份", "encry" => false],
        ["keys" => 'ip', "value" => "访问ip", "encry" => false],
        ["keys" => 'spreadManager', "value" => "推广经理", "encry" => false],
        ["keys" => 'keyword', "value" => "关键词/创意", "encry" => false],
        ["keys" => 'unit', "value" => "单元", "encry" => false],
        ["keys" => 'plan', "value" => "计划", "encry" => false],
        ["keys" => 'address', "value" => "详细地址", "encry" => false],
        ["keys" => 'gender', "value" => "性别", "encry" => false],
        ["keys" => 'age', "value" => "年龄", "encry" => false],
        ["keys" => 'referer', "value" => "落地页链接", "encry" => false],
        ["keys" => 'toutiaoTrafficSource', "value" => "流量来源", "encry" => false],
        ["keys" => 'dealCount', "value" => "成交次数", "encry" => false],
        ["keys" => 'firstTrackTime', "value" => "首次跟单时间", "encry" => false],
        ["keys" => 'appointmentCount', "value" => "预约次数", "encry" => false],
        ["keys" => 'appointmentStatus', "value" => "预约状态", "encry" => false],
        ["keys" => 'search_key', "value" => "搜索词", "encry" => false],
        ["keys" => 'callNum', "value" => "拨打次数", "encry" => false],
        ["keys" => 'lastCallConnectedTime', "value" => "最近接通时间", "encry" => false],
        ["keys" => 'earliestValidCallConnectedTime', "value" => "首次有效通话时间", "encry" => false],
        ["keys" => 'callConnectedNum', "value" => "接通次数", "encry" => false],
        ["keys" => 'validCallNum', "value" => "有效通话次数", "encry" => false],
        ["keys" => 'earliestCallTime', "value" => "首次通话时间", "encry" => false],
        ["keys" => 'lastValidCallConnectedTime', "value" => "最近有效通话时间", "encry" => false],
        ["keys" => 'earliestCallConnectedTime', "value" => "首次接通时间", "encry" => false],
        ["keys" => 'ofc_1', "value" => "广告商", "encry" => false],
        ["keys" => 'ofc_2', "value" => "推广账户", "encry" => false],
        ["keys" => 'ofc_6', "value" => "站点名称", "encry" => false],
        ["keys" => 'ofc_3', "value" => "推广类型", "encry" => false],
        ["keys" => 'qq_number', "value" => "QQ号", "encry" => true],
        ["keys" => 'wechart', "value" => "微信号", "encry" => true],
        ["keys" => 'level', "value" => "线索等级", "encry" => false],
        ["keys" => 'recentSale', "value" => "最近归属人", "encry" => false],
        ["keys" => 'delReason', "value" => "删除原因", "encry" => false],
        ["keys" => 'first_allot_time', "value" => "首次归属时间", "encry" => false],
        ["keys" => 'first_sign_time', "value" => "首次成交单时间", "encry" => false],
        ["keys" => 'repeatInputTime', "value" => "重复录入时间", "encry" => false],
        ["keys" => 'sourceSchool', "value" => "网校分校", "encry" => false],
        ["keys" => 'dropReason', "value" => "放弃原因", "encry" => false],
        ["keys" => 'consultType', "value" => "线索来源", "encry" => false],
        ["keys" => 'equip', "value" => "设备", "encry" => false],
        ["keys" => 'channel', "value" => "渠道", "encry" => false],
        ["keys" => 'tag', "value" => "标签", "encry" => false],
        ["keys" => 'lastCallTime', "value" => "最近通话时间", "encry" => false],
        ["keys" => 'backTime', "value" => "回库倒计时", "encry" => false],
        ["keys" => 'getType', "value" => "机会获得方式", "encry" => false],
        ["keys" => 'creator', "value" => "录入人", "encry" => false],
        ["keys" => 'trackNum', "value" => "跟单次数", "encry" => false],
        ["keys" => 'backNum', "value" => "回库次数", "encry" => false],
        ["keys" => 'signTime', "value" => "最近成交单时间", "encry" => false],
        ["keys" => 'reserveTime', "value" => "定金时间", "encry" => false],
        ["keys" => 'deleteTime', "value" => "删除时间", "encry" => false],
        ["keys" => 'dropTime', "value" => "放弃时间", "encry" => false],
        ["keys" => 'transferTime', "value" => "转人时间", "encry" => false],
        ["keys" => 'nextTrackTime', "value" => "下次跟进时间", "encry" => false],
        ["keys" => 'lastTrackTime', "value" => "最近工单时间", "encry" => false],
        ["keys" => 'allotTime', "value" => "机会获得时间", "encry" => false],
        ["keys" => 'createTime', "value" => "客户创建时间", "encry" => false],
        ["keys" => 'customerRegistTime', "value" => "注册时间", "encry" => false],
        ["keys" => 'customerStatus', "value" => "客户状态", "encry" => false],
        ["keys" => 'customerLevel', "value" => "客户意向", "encry" => false],
        ["keys" => 'customerSource', "value" => "客户来源", "encry" => false],
        ["keys" => 'customerType', "value" => "客户类型", "encry" => false],
        ["keys" => 'contactPhone', "value" => "手机号码", "encry" => true],
        ["keys" => 'customerName', "value" => "客户姓名", "encry" => false],
        ["keys" => 'idCard', "value" => "身份证号", "encry" => true],
        ["keys" => 'saleUserName', "value" => "销售账户名", "encry" => false],
        ["keys" => 'recentSaleUserName', "value" => "最近归属人账户名", "encry" => false],
        ["keys" => 'firstBelongSaleUserName', "value" => "首次归属人账户名", "encry" => false]

    );
    public $customer = array(
        ['keys' => "leads_type", "value" => '线索类型', 'encry' => false],
        ['keys' => "leadsCreateTime", "value" => '线索获取时间', 'encry' => false],
        ['keys' => "contactPhone", "value" => '手机号码', 'encry' => true],
        ['keys' => "wechart", "value" => '微信号', 'encry' => true],
        ['keys' => "equip", "value" => '设备', 'encry' => false],
        ['keys' => "sourceType", "value" => '资源类型', 'encry' => false],
        ['keys' => "creator", "value" => '录入人', 'encry' => false],
        ['keys' => "mgid", "value" => '消息id', 'encry' => false],
        ['keys' => "trackNum", "value" => '跟单次数', 'encry' => false],
        ['keys' => "customer_from", "value" => '客户来源', 'encry' => false],
        ['keys' => "backNum", "value" => '回库次数', 'encry' => false],
        ['keys' => "spreadCity", "value" => '线索城市', 'encry' => false],
        ['keys' => "id", "value" => 'ID', 'encry' => false],
        ['keys' => "status", "value" => '状态', 'encry' => false],
        ['keys' => "entrySource", "value" => '输入源', 'encry' => false],
        ['keys' => "referer", "value" => '落地页链接', 'encry' => false],
        ['keys' => "seq", "value" => 'seq', 'encry' => false],
        ['keys' => "createTime", "value" => '客户创建时间', 'encry' => false],
        ['keys' => "spreadManager", "value" => '推广经理', 'encry' => false],
        ['keys' => "ip", "value" => 'IP', 'encry' => false],
        ['keys' => "sourceName", "value" => 'sourceName', 'encry' => false],
        ['keys' => "customerName", "value" => '客户姓名', 'encry' => false],
        ['keys' => "belongStatus", "value" => '分配状态', 'encry' => false],
        ['keys' => "ofc_2", "value" => 'ofc_2', 'encry' => false],
        ['keys' => "spreadProvince", "value" => '线索省份', 'encry' => false],
        ['keys' => "ofc_1", "value" => 'ofc_1', 'encry' => false],
        ['keys' => "ofc_3", "value" => 'ofc_3', 'encry' => false],
        ['keys' => "ofc_6", "value" => 'ofc_6', 'encry' => false],
        ['keys' => "unit", "value" => '单元', 'encry' => false],
        ['keys' => "marketingCostType", "value" => 'marketingCostType', 'encry' => false],
        ['keys' => "sourceOwnerId", "value" => '持有人ID', 'encry' => false],
        ['keys' => "creativeId", "value" => 'creativeId', 'encry' => false],
        ['keys' => "plan", "value" => '计划', 'encry' => false],
    );

    public function index()
    {
//        */5 9-20 * * *  每天9-20点每隔五分钟执行一次 实时分配
//        * 9 * * *    每天9点执行一次  库存分配分配过去13个小时积累的数据
        $timeLevel=input('timeLevel')?input('timeLevel'):0;
        if($timeLevel==1){
            //库存分配
            $offset=13*3600+30;//向前查询30秒
        }else{
            //实时分配
            $offset=5*60+15;//向前查询15秒
        }
        $start=date("Y-m-d H:i:s",time()-$offset);
        $end=date("Y-m-d H:i:s");
        $manage=new Manage();
        $manage->runRealtimeAllocation($offset);
        /*$this->pullData($start,$end,1);
        dump($this->customerList);*/
//        $this->getSaler();
    }

    public function getSaler()
    {
        $times = time();
        $signature = $this->getSignature($times);
//        dump($signature);
        $header = array(
            'Content-Type:application/json',
            'timestamp:' . $times,
            'accessToken:' . $this->token,
            'signature:' . $signature,
        );
        $data = array();
        $url = "https://outcrmapi.yunduocrm.com/api/dataSync/getSalesInfoOfAutoAllotRuleConfig/2015?router_id=2015";
        $data['auto_allot_rule_name'] = "汉语教师实时分配";
        $data['auto_allot_rule_type'] = 0;
        $data=json_encode($data);
        file_put_contents('./input.log',$data);
        file_put_contents('./header.log',json_encode($header));
        $res=$this->postData($data,$header,$url);
        file_put_contents('./output.log',$res);
        $result=json_decode($res,true);
        if($result['code']==200 && isset($result['data'])){
            $list=$result['data'];
            $this->initSaler($list);
            return $result['data'];
        }
    }

    private function pullData($start,$end,$p)
    {
        set_time_limit(0);
        /*每页50条数据*/
        $url="https://outcrmapi.yunduocrm.com/api/dataSync/findCustomerByCreateTime/2015?router_id=2015";
        $times=microtime(true);
        $times=time();
        $signature=$this->getSignature($times);
//        dump($signature);
        $header = array(
            'Content-Type:application/json',
            'timestamp:' . $times,
            'accessToken:' . $this->token,
            'signature:' . $signature,
        );
        $data=array();
        $data['beginTime']=$start;
        $data['endTime']=$end;
        $data['pageNum']=$p;
        $data=json_encode($data);
        $res=$this->postData($data,$header,$url);
        $res=json_decode($res,true);
        halt($res);
        if($res['code']==200 && isset($res['data']['customerList'])){
            $list=$res['data']['customerList'];
            $p++;
            $this->setData($list);
            $this->pullData($start,$end,$p);
        }
    }

    public function setData($list)
    {
        $fileList = $this->file_val;
        $cusFiled = $this->customer;
        foreach ($list as $v) {
            if(isset($v['belongStatus']) && $v['belongStatus']=="无归属"){
//                dump($v);
                $data=array();
                foreach ($cusFiled as $vs){
                    $keys=$vs['keys'];
                    $data[$keys]=isset($v[$keys])?$v[$keys]:"";
                }
                $list=db('customer')->where('id',$v['id'])->find();
                $this->customerList[]=$v;
                if(empty($list)){
                    db('customer')->insert($data);
                }
            }else {
//                dump($v);
                $list = db('customer_1')->where('c_id', $v['uniqueCustomerId'])->find();
                if ($list) {
                    continue;
                }
                $i = 0;
                $j = 1;
                $data = array();
                $data['c_id'] = $v['uniqueCustomerId'];
                foreach ($fileList as $vf) {
                    $i++;
                    $keys = $vf['keys'];
                    $data[$keys] = isset($v[$keys]) ? $v[$keys] : "";
                    if ($i % 45 == 0) {
                        db("customer_" . $j)->insert($data);
                        $j++;
                        $data = array();
                        $data['c_id'] = $v['uniqueCustomerId'];
                    }
                }
                db("customer_" . $j)->insert($data);
            }
        }
    }

    public function downloadXs()
    {
        $list = db('customer_1')->select();
        $filesList = $this->customer;
        $files = array_column($filesList, "value");
        $str = rtrim(implode(",", $files), ",") . "\n";
        foreach ($list as $v) {
            $strc = "";
            foreach ($filesList as $vf) {
                $keys = $vf['keys'];
                $value = isset($v[$keys]) ? str_replace([",", "\n"], ['', ''], $v[$keys]) : "";
                if ($vf['encry']) {
                    $value = md5($keys . $value);
                }
                $strc .= $value;
                $strc .= ",";
            }
            $str .= str_replace("\n", "", rtrim($strc, ",")) . "\n";
        }
        $filename = '20211229线索数据.csv';
        export_csv($filename, $str);
    }

    public function downLoad()
    {
        //30
        set_time_limit(0);
        $p = input('p');
//        dump($p);
        $list = db('customer_1')->order('addtime desc')->paginate(5000, 1, ['page' => $p]);
        $filesList = $this->file_val;
        $files = array_column($filesList, "value");
        $str = rtrim(implode(",", $files), ",") . "\n";
        foreach ($list as $v) {
            $strc = "";
            $list2 = db('customer_2')->where('c_id', $v['c_id'])->find();
            $list3 = db('customer_3')->where('c_id', $v['c_id'])->find();
            $all = array_merge($v, $list2, $list3);
            foreach ($filesList as $vf) {
                $keys = $vf['keys'];
                $value = $all[$keys] ? str_replace([",", "\n"], ['', ''], $all[$keys]) : "";
                if ($vf['encry']) {
                    $value = md5($keys . $value);
                }
                $strc .= $value;
                $strc .= ",";
            }
            $str .= str_replace("\n", "", rtrim($strc, ",")) . "\n";
//            halt($str);
        }
        $filename = date("Ymd") . "_" . $p . '.csv';
        export_csv($filename, $str);
    }

    private function createTable($tableName = "", $data = "")
    {
        if (!$tableName || !$data) {
            return false;
        }
        $sql_var = "";
        $i = 0;
        $j = 1;
        foreach ($data as $v) {
            if ($v) {
                $i++;
                $sql_var .= "{$v['keys']} VARCHAR(300) COMMENT '{$v['value']}',";
                if ($i % 45 == 0) {
                    $this->create($sql_var, $tableName . "_" . $j);
                    $j++;
                    $sql_var = "";
                }
            }
        }
        $this->create($sql_var, $tableName . "_" . $j);

    }

    private function create($sql, $tableName)
    {
        $sql = "CREATE TABLE $tableName (
               id int NOT NULL AUTO_INCREMENT, 
               c_id int NOT NULL , 
               PRIMARY KEY(id), 
               {$sql}
               addtime varchar(15) COMMENT '添加时间'
               )ENGINE=MyISAM DEFAULT CHARSET=utf8";
        db()->query($sql);
    }

    /*获取云朵第一次同步数据数据并分发数据*/
    public function receiveInitData()
    {
        //接收数据
        $data = array();
        $data['phone'] = input('phone') ? input('phone') : "";
        $data['name'] = input('name') ? input('name') : "";
        $data['grep'] = input('grep') ? input('grep') : "";
        if (!$data['phone']) {
            return json(['code' => 2, 'msg' => "请输入电话号码"]);
        }
        //分发数据
        $this->distributeData($data);
        return json(['code' => 1, 'msg' => "数据已录入"]);
    }

    /*分发数据操作*/
    private function distributeData($data = "")
    {
        $redis = new Redis(config('redis'));
        $distribute_num = $redis->get("distribute_num");
        if (!$distribute_num) {
            $distribute_num = 0;
        }
        $distribute_rate = $redis->get("distribute_rate");
        if (!$distribute_rate) {
            $distribute_rate = "1:1";
        }
        $distribute_rate_arr = explode(":", $distribute_rate);
        $rateSum = $distribute_rate_arr[0] + $distribute_rate_arr[1];
        $res = $distribute_num % $rateSum;
        $salerData = array();
        $salerData['contactPhone'] = $data['phone'];
        if ($res < $distribute_rate_arr[0]) {
            //分发测试数据 测试数据本地存储一份，分发一份给打分系统，获取分发结果
            $receive = new Receive();
            $receive->receiveHandleData();
            //按照分发结果绑定销售
            $data['dis_type'] = 2;
        } else {
            //分发对照数据 对照数据直接存储本地
            //本地分配销售
            $saler = $this->initSaler();
            $salerData['saleUserName'] = $saler['username'];
        }
        //自增计数
        if ($distribute_num == 0) {
            $redis->set("distribute_num", 1);
        } else {
            $redis->inc('distribute_num');
        }
        $redis->inc(date("Y_m_d"));
        //同步销售绑定
        $bindResult = $this->bindSaler($salerData);
    }

    /*更新销售数据*/
    private function initSaler($list)
    {
        foreach($list as $v){
            if($v['saleId']){
                $saler=db('saler')->where('saleId',$v['saleId'])->find();
                if($saler){
                    db('saler')->where('saleId',$v['saleId'])->update($v);
                }else{
                    db('saler')->insert($v);
                }

            }
        }

    }

    private function save($data)
    {
        $data['add_time'] = date('Y-m-d H:i:s');
        db('crm_data')->insert($data);
    }

    /*绑定销售*/
    private function bindSaler($data)
    {
        $url = "https://outcrmapi.yunduocrm.com/api/dataSync/customerTransfer/2015?router_id=2015";
        $times = time();
        $signature = $this->getSignature($times);
        $header = array(
            'timestamp:' . $times,
            'accessToken:' . $this->token,
            'signature:' . $signature,
            /*'Content-Type: application/json;charset=UTF-8',
            'Content-Length:' . strlen($postdata)*/
        );
        $data = json_encode($data);
        $res = $this->postData($data, $header, $url);
        return json_decode($res, true);

    }

    private function get_rand($proArr)
    {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        // var_dump($proSum);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum); //返回随机整数

            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }

    private function getSignature($times)
    {
        $company_id = "2015";
        $token=$this->token;
        $key = $times . $company_id;
        return bin2hex(hash_hmac("sha256", $token, $key, true));
    }

    private function postData($content, $header, $url)
    {

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);  //设置url
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在 设为0表示不检查证书 设为1表示检查证书中是否有CN(common name)字段 设为2表示在1的基础上校验当前的域名是否与CN匹配
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST'); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
        curl_setopt($curl, CURLOPT_TIMEOUT, 0); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回


        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
}